util = require 'util'
mongoose = require 'mongoose'

cfg =require './cfg'
config = require '../../config'

# NODE环境
ENV = config.env
# DB参数配置
db_conf = cfg[ENV]

# 获得连接URL
getDbUrl = () ->
  # 连接URL
  tmpUrl = ''
  if 'production' is ENV
    tmpUrl = util.format("mongodb://%s:%s@%s:%d/%s", db_conf.user, db_conf.pass, db_conf.host, db_conf.port, db_conf.name)
  else if 'test' is ENV
    tmpUrl = util.format("mongodb://%s:%s@%s:%d/%s", db_conf.user, db_conf.pass, db_conf.host, db_conf.port, db_conf.name)
  else
    if 'localhost' is db_conf?.host
      # 无密码
      tmpUrl = util.format("mongodb://%s:%s/%s", db_conf.host, db_conf.port, db_conf.name)
    else
      # 有密码
      tmpUrl = util.format("mongodb://%s:%s@%s:%d/%s", db_conf.user, db_conf.pass, db_conf.host, db_conf.port, db_conf.name)

  return tmpUrl

mongoose.Promise = global.Promise

# mongoose.connect getDbUrl(), {auth:{authdb: db_conf.name}}
mongoose.connect getDbUrl(), {useMongoClient: true}

mongoose.connection.on 'connected', ->
  console.log "Mongoose connected to #{getDbUrl()}"

mongoose.connection.on 'error', (err) ->
  console.log "Mongoose connection error: #{err}"

mongoose.connection.on 'disconnected', ->
  console.log "Mongoose disconnected"

process.on 'SIGINT', ->
  mongoose.connection.close ->
    console.log "Mongoose disconnected through app termination"
    process.exit 0

module.exports.getDbUrl = getDbUrl

module.exports.mongoose = mongoose

module.exports.Schema = mongoose.Schema

module.exports.Types = mongoose.Types

module.exports.mongoose_plugins =
  updated_at : (schema, options) ->

    schema.add
      updated_at : Date

    schema.pre 'save', (next) ->
      # 注意：进行时区校正
      @updated_at = new Date(new Date().getTime() + 3600000 * 8)
      return next()

    if options?.index
      schema.path('updated_at').index options.index